import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import '../../helper/Helper.dart';

import '../../helper/global_config.dart';
import '../../pages/things/things_helper.dart';
import '../../model/inventory.dart';
import '../../helper/routeHelper.dart';

class InventoryListPage extends StatefulWidget {
  final bool ifAppbar;
  final int sType;
  @override
  InventoryListPage(this.ifAppbar, this.sType);
  @override
  InventoryListPageState createState() => new InventoryListPageState();
}

class InventoryListPageState extends State<InventoryListPage> {
  List<Inventory> RList = <Inventory>[];
  bool isEnd = false;
  ScrollController _scrollController = new ScrollController();
  bool firstLoading = false;
  int canShow = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        getMore();
      }
    });

    getNewer();
  }

  Future<Null> delete(Inventory r1) async {
    // await addOne();

    await Inventory.Delete(r1);
    setState(() {
      RList.remove(r1);
    });
  }

  onDeleted(Inventory r1) => {
        setState(() {
          RList.remove(r1);
        })
      };

  Future<Null> getMore() async {
    // await addOne();
    int count = 5;
    if (isEnd == true) return;
    int page = RList.length ~/ count;
    var list1 =
        await Inventory.GetListByType(widget.sType, canShow, page + 1, count);
    var list2 =
        list1.where((p) => RList.any((x) => x.ID == p.ID) == false).toList();

    setState(() {
      if (list1.length < count) isEnd = true;
      RList.insertAll(RList.length, list2);
    });
  }

  Future<Null> getRefrush() async {
    var list1 = await Inventory.GetListByType(widget.sType, canShow, 1, 20);

    setState(() {
      RList = list1;
    });
  }

  Future<Null> getNewer() async {
    var list1 = await Inventory.GetListByType(widget.sType, canShow, 1, 5);
    setState(() {
      firstLoading = false;
    });

    if (list1.length == 0) return;

    var list2 =
        list1.where((p) => RList.any((x) => x.ID == p.ID) == false).toList();
    if (list2.length == 0) return;

    list2.insertAll(list2.length, RList);

    setState(() {
      firstLoading = false;
      RList = list2;
    });
  }

  String getTitle() {
    if (widget.sType == 0) return "入库单";
    if (widget.sType == 1) return "出库单";
    if (widget.sType == 2) return "借出单";
    if (widget.sType == -1) return "物管单";
    return "出错！";
  }

  Widget InventoryCard(Inventory x1) {
    return Card(
        key: Key(x1.ID.toString()),
        margin: const EdgeInsets.only(top: 0.2, bottom: 0.2),
        color: GlobalConfig.cardBackgroundColor,
        shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
        child: ListTile(
          //leading: ImageWidget.StationImage(StationList[index].Name),
          title: Text(x1.TName),
          //trailing: Text(StationList[index].STCD),
          onTap: () {
            //   RouteHelper(context, station);
          },
          onLongPress: () {
            // RouteHelper.InventoryAdd(context,x1, getRefrush);
          },
        ));
  }

  @override
  Widget build(BuildContext context) {
    if (RList == null) return new Container();
    // TODO: implement build
    return new Scaffold(
        appBar: widget.ifAppbar
            ? AppBar(
                title: Text(getTitle() + "列表"),
                actions: <Widget>[
                  Helper.AuthPB("物资管理")
                      ? IconButton(
                          icon: Icon(
                            Icons.add,
                            color: Colors.white,
                          ),
                          onPressed: () {
                            RouteHelper.InventoryAdd(context, "新建" + getTitle(),
                                widget.sType, getRefrush);
                          })
                      : Container(),
                ],
              )
            : null,
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.refresh),
          onPressed: () => getRefrush(),
        ),
        body: firstLoading == true
            ? Center(
                child: SpinKitCircle(
                color: Colors.blue,
              ))
            : Container(
                margin: EdgeInsets.only(top: 8.0),
                child: new RefreshIndicator(
                  child: ListView.builder(
                    itemCount: RList.length + 1,
                    controller: _scrollController,
                    physics: const AlwaysScrollableScrollPhysics(),
                    itemBuilder: (BuildContext context, int index) {
                      if (index != RList.length) {
                        return ThingsHelper.InventoryCard(
                            context, RList[index], getRefrush);
                      } else {
                        if (isEnd == true) {
                          return Container(
                              margin: EdgeInsets.all(12.0),
                              child: Center(
                                  child: Text(
                                "没有更多了",
                                style: TextStyle(color: Colors.grey),
                              )));
                        } else {
                          return new Container();
                        }
                      }
                    },
                  ),
                  onRefresh: getNewer,
                )));
  }
}
